package com.android.monee.data.access.inMemory;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.android.monee.data.access.GenericDao;
import com.android.monee.data.access.IdNClone;

public abstract class AbstractDaoInMemory<T extends IdNClone<I, T>, I> implements GenericDao<T, I> {
	
	protected Map<I, T> datas = new HashMap<I, T>();
	
	//TODO : faire une fonction insert(Collection<T> obj);
	
	@Override
	public T findById(I id) {
		T found = datas.get(id);
		if(found != null)
			return found.clone();
		else
			return null;
	}

	@Override
	public List<T> findAll() {
		ArrayList<T> res = new ArrayList<T>();
		for (T val : datas.values()){
			res.add(val.clone());
		}
		return res;
	}

	@Override
	public void insert(T obj){
		obj.setId(getNextId());
		datas.put(obj.getId(), obj.clone());
	}

	abstract protected I getNextId();
	
	@Override
	public void update(T obj) {
		datas.put(obj.getId(), obj.clone());
	}

	@Override
	public void delete(I id) {
		datas.remove(id);		
	}
}
